<?php

namespace app\order\logic;

use app\common\library\Excel;
use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Config;
use Throwable;
use app\common\service\ConstantOrderService;
use app\order\model\Order as OrderModel;
use think\facade\Db;


class OrderShipLogic
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new OrderModel();
    }

    public function getOrderShiopList($params = [])
    {

        $shop_id         = $params['shop_id'] ?? '0';
        $orderId         = $params['order_id'] ?? '';
        $seller_sku      = $params['skus_info'] ?? '';
        $status          = $params['status'] ?? '';
        $shipping_type   = $params['shipping_type'] ?? '';
        $tracking_number = $params['tracking_number'] ?? '';
        $warehouse_id    = $params['warehouse_id'] ?? '';
        $createtime      = $params['createtime'] ?? '';
        $ship_time       = $params['ship_time'] ?? '';

        $brush_status    = $params['brush_status'] ?? '';
        $limit           = $params['limit'] ?? 10;

        $where           = [];
        $order = ['order.createtime' => 'desc', 'order.id' => 'desc'];


        if ($orderId) {
            $order_ids = trim($orderId);
            $order_ids = array_filter(array_map('trim', explode("\n", $order_ids)));
            if (!empty($order_ids)) {
                $where[] = ['order.order_id', 'in', $order_ids];
            }
        }

        if ($shop_id) {
            $where[] = ['order.shop_id', '=',$shop_id];
        }

        if($seller_sku) {
            $orderIds = Db::name('order_info')
                ->where('seller_sku', 'like', '%' . $seller_sku . '%')
                ->column('order_id');
            $orderIds = array_unique($orderIds);
            if ($orderIds) {
                $where[] = ['order.order_id', 'in', $orderIds];
            }
        }

        //update 2024-05-09 异常重发页面
        if($status == 6){
            $map = [];
            return self::get_status_six($map,$limit,$warehouse_id,$orderId);
        }

        if ($status) {
            $where[] = ['ship.status', '=', $status];
        }else{
            $where[] = ['ship.status', '>=', 1];
        }

        if ($brush_status) {
            $where[] = ['order.brush_status', '=', $brush_status];
        }

        if ($shipping_type) {
            $where[] = ['order.shipping_type', '=', $shipping_type];
        }


        if ($tracking_number) {
            $where[] = ['order.tracking_number', 'like', '%' . $tracking_number . '%'];
        }
        if ($warehouse_id) {
            $where[] = ['ship.warehouse_id', '=', $warehouse_id];
        }
        if ($createtime) {
            $createTimeArr = explode(',', $createtime);
            $where[] = ['order.createtime', '>=', strtotime($createTimeArr[0])];
            $where[] = ['order.createtime', '<=', strtotime($createTimeArr[1])];
        }
        if ($ship_time) {
            $shipTimeArr = explode(',', $ship_time);
            $where[] = ['ship.time', '>=', strtotime($shipTimeArr[0])];
            $where[] = ['ship.time', '<=', strtotime($shipTimeArr[1])];
        }

        $field = [
            'order.id','order.order_id','order.shop_id','ship.warehouse_id',
            'ship.status as ship_status','ship.time as ship_time','ship.msg','ship.type',
            'order.createtime','order.brush_status','order.tracking_number','order.status as order_status',
            'appends.name','appends.phone_number','order.shipping_type'
        ];

        $res =  Db::name('order')
            ->alias('order')
            ->leftJoin('ba_order_append appends', 'order.order_id = appends.order_id')
            ->leftJoin('ba_order_ship ship', 'order.order_id = ship.order_id')
            ->field($field)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $list = $res->items()?:[];
        $shop_ids  = array_column($list,'shop_id');
        $shop_ids  = array_values(array_unique($shop_ids));

        $order_ids = array_column($list,'order_id');
        $order_ids = array_values(array_unique($order_ids));


        //批量获取店铺信息及sku数量信息;
        $shopInfos     = Db::name('shops')->whereIn('id',$shop_ids)->field('name,id')->select();
        $shopInfos     = objectToArray($shopInfos);
        $shopInfos_map = array_column($shopInfos,null,'id');

        //批量获取sku数量数据;
        $skuInfos     = Db::name('order_info')->whereIn('order_id',$order_ids)->field('seller_sku,order_id')->select();
        $skuInfos     = objectToArray($skuInfos);
        $skuInfos_map = self::get_sku_info($skuInfos);
        $info         = Config::get('Logisticskey.' . 'warehouse_arr_old');
        $brush_info   = Config::get('Logisticskey.' . 'brush_list');
        $ship_info    = Config::get('Logisticskey.' . 'ship_status');
        if($list){
            foreach($list as $k=>$v){
                if(isset($v['warehouse_id']) && $v['warehouse_id']==3){
                    $message    = json_decode($v['msg'],true);
                    $message    = $message['Message']??$v['msg'];
                }elseif(isset($v['warehouse_id']) && $v['warehouse_id']==4){
                    $message    = json_decode($v['msg'],true);
                    $message    = $message['msg']??$v['msg'];
                }else{
                    $message    = $v['msg'];
                }

                $shop_names = $shopInfos_map[$v['shop_id']]??[];
                $sku_names  = $skuInfos_map[$v['order_id']]??[];
                $list[$k]['shop_name']     =  $shop_names['name']??'';
                $list[$k]['skus_info']     =  $sku_names ? implode(',',$sku_names):'';
                $list[$k]['warehouse_name']=  $v['warehouse_id'] ? $info[$v['warehouse_id']]:'';
                $list[$k]['brush_status']  =  $v['brush_status'] ? $brush_info[$v['brush_status']]:'';
                $list[$k]['ship_status']   =  $v['ship_status']  ? $ship_info[$v['ship_status']]:'';
                $list[$k]['msg']           = $message??'';
            }
        }

        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    public function editOrder($data)
    {
         $sku_info = $data['skus_info']??'';
         if (!$sku_info) {
            return json(DefaultResponse(201, false, 'sku不能为空!', null));
         }
         $sku_info   = explode(',',$sku_info);
         foreach($sku_info as $v){
             if(!$v)  continue;
             $exist_info = Db::name('order_split_ship')->where(['order_id'=>$data['order_id'],'seller_sku'=>$v])->order('id DESC')->find();
             if(!$exist_info){
                 $insertInfo = [
                     'order_id'     =>$data['order_id']??'',
                     'shop_id'      =>$data['shop_id']??'',
                     'seller_sku'   =>str_replace("\n", "", $v),
                     'spu'          =>get_spu_info($v),
                     'num'          =>get_colours_num($v),
                     'created_time' =>date('Y-m-d H:i:s',time()),
                 ];
                 Db::name('order_split_ship')->insert($insertInfo);
             }else{
                 Db::name('order_split_ship')->where('id',$exist_info['id'])->update(['status'=>0,'created_time'=>date('Y-m-d H:i:s',time())]);
             }
         }
        Db::name('order_ship')->where('order_id',$data['order_id'])->update(['status'=>5]);
        return json(DefaultResponse(200, true, '操作成功', null));
    }



    /**
     * @desc 异常补发编辑接口
     * @date  2024/5/09
     */
    public function editSplitOrder($data=[]){
        $id              = $data['id']??'';
        $order_id        = $data['order_id']??'';
        $skus_info       = $data['skus_info']??'';
        $sku_info        = explode(',',$skus_info);
        $num             = count($sku_info);
        if($num<=1){
            $append_info = [
                'name'               => $data['name']??'',
                'phone_number'       => $data['phone_number']??'',
                'postal_code'        => $data['postal_code']??'',
                'region_code'        => $data['region_code']??'',
                'county'             => $data['county']??'',
                'address_detail'     => $data['address_detail']??'',
                'buyer_email'        => $data['buyer_email']??'',
            ];
            $skus_info =str_replace("\n", "", $skus_info);
            Db::name('order_split_ship')->where('id',$id)->update(
                ['seller_sku'=>$skus_info,'update_time'=>date("Y-m-d H:i:s", time()),]
            );
            Db::name('order_append')->where('order_id',$order_id)->update($append_info);
        }else{
            foreach($sku_info as $v){
                if(!$v)  continue;
                $exist_info = Db::name('order_split_ship')->where(['order_id'=>$data['order_id'],'seller_sku'=>$v])->find();
                if(!$exist_info){
                    $insertInfo = [
                        'order_id'     =>$data['order_id']??'',
                        'shop_id'      =>$data['shop_id']??'',
                        'seller_sku'   =>str_replace("\n", "", $v),
                        'spu'          =>get_spu_info($v),
                        'num'          =>get_colours_num($v),
                        'created_time' =>date('Y-m-d H:i:s',time()),
                    ];
                    Db::name('order_split_ship')->insert($insertInfo);
                }
            }
            Db::name('order_ship')->where('order_id',$data['order_id'])->update(['status'=>5]);
            Db::name('order_split_ship')->where('id',$id)->update(['status'=>1,'update_time'=>date("Y-m-d H:i:s", time())]);
        }


    }





    /**
     * @desc 异常补发页面接口
     * @date  2024/5/09
     */
    private function get_status_six($where=[],$limit='',$warehouse_id='',$orderId=''){
        $field = ['id','order_id','shop_id','warehouse_id','seller_sku','update_time', 'created_time','msg'];
        $order   = ['created_time' => 'desc', 'id' => 'desc'];
        $where[] = ['status', '=', 0];

        if ($warehouse_id) {
            if($warehouse_id == 1){
                $where[] = ['warehouse_id', '=', ''];
            }else{
                $where[] = ['warehouse_id', '=', $warehouse_id];
            }
        }


        if($orderId){
            $where[] = ['order_id', '=', $orderId];
        }


        $res = Db::name('order_split_ship')
            ->field($field)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $list = $res->items()?:[];

        $shop_ids  = array_column($list,'shop_id');
        $shop_ids  = array_values(array_unique($shop_ids));
        $order_ids = array_column($list,'order_id');
        $order_ids = array_values(array_unique($order_ids));


        //批量获取店铺信息;
        $shopInfos     = Db::name('shops')->whereIn('id',$shop_ids)->field('name,id')->select();
        $shopInfos     = objectToArray($shopInfos);
        $shopInfos_map = array_column($shopInfos,null,'id');

        $appends       = Db::name('order_append')->whereIn('order_id',$order_ids)->field('name,phone_number,order_id')->select();
        $appends       = objectToArray($appends);
        $appends_map   = array_column($appends,null,'order_id');

        $ships         = Db::name('order_ship')->whereIn('order_id',$order_ids)->field('status as ship_status,time as ship_time,msg,type,order_id')->select();
        $ships         = objectToArray($ships);
        $ships_map     = array_column($ships,null,'order_id');

        $orders        = Db::name('order')->whereIn('order_id',$order_ids)->field('status as order_status,brush_status,shipping_type,tracking_number')->select();
        $orders        = objectToArray($orders);
        $orders_map    = array_column($orders,null,'order_id');



        $info         = Config::get('Logisticskey.' . 'warehouse_arr');
        $brush_info   = Config::get('Logisticskey.' . 'brush_list');
        $ship_info    = Config::get('Logisticskey.' . 'ship_status');

        if($list){
            foreach($list as $k=>$v){
                $shop_names    = $shopInfos_map[$v['shop_id']]??[];
                $appends_names = $appends_map[$v['order_id']]??[];
                $ships_names   = $ships_map[$v['order_id']]??[];
                $orders_info   = $orders_map[$v['order_id']]??[];
                $list[$k]['shop_name']     =  $shop_names['name']??'';
                $list[$k]['name']          =  $appends_names['name']??'';
                $list[$k]['phone_number']  =  $appends_names['phone_number']??'';
                $ship_status               =  $ships_names['ship_status']??'';
                $list[$k]['ship_status']   =  $ship_status  ? $ship_info[$ship_status]:'';
                $list[$k]['ship_time']     =  $v['update_time']??'';
                $list[$k]['createtime']    =  $v['created_time']??'';

                $brush_status     =  $orders_info['brush_status']??'';
                $list[$k]['tracking_number']  =  $orders_info['tracking_number']??'';
                $list[$k]['order_status']     =  $orders_info['order_status']??'';
                $list[$k]['shipping_type']    =  $orders_info['brush_status']??'';

                $list[$k]['msg']           =  $v['msg']??'';
                $list[$k]['type']          =  $ships_names['type']??'';
                $list[$k]['skus_info']     =  $v['seller_sku'];
                $list[$k]['warehouse_name']=  $v['warehouse_id'] ? $info[$v['warehouse_id']]:'';
                $list[$k]['brush_status']  =  $brush_status ? $brush_info[$brush_status]:'';
            }
        }

        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }


    /**
     * @desc 异常补发页面导出接口
     * @date  2024/5/16
     */
    private function get_export_six($where=[],$limit='',$warehouse_id='',$orderId=''){
        $field = ['id','order_id','shop_id','warehouse_id','seller_sku','update_time', 'created_time','msg'];
        $order   = ['created_time' => 'desc', 'id' => 'desc'];
        $where[] = ['status', '=', 0];

        if ($warehouse_id) {
            if($warehouse_id == 1){
                $where[] = ['warehouse_id', '=', ''];
            }else{
                $where[] = ['warehouse_id', '=', $warehouse_id];
            }
        }


        if($orderId){
            $where[] = ['order_id', '=', $orderId];
        }


        $res = Db::name('order_split_ship')
            ->field($field)
            ->where($where)
            ->order($order)
            ->select();

        $list = objectToArray($res);

        $shop_ids  = array_column($list,'shop_id');
        $shop_ids  = array_values(array_unique($shop_ids));
        $order_ids = array_column($list,'order_id');
        $order_ids = array_values(array_unique($order_ids));


        //批量获取店铺信息;
        $shopInfos     = Db::name('shops')->whereIn('id',$shop_ids)->field('name,id')->select();
        $shopInfos     = objectToArray($shopInfos);
        $shopInfos_map = array_column($shopInfos,null,'id');

        $appends       = Db::name('order_append')->whereIn('order_id',$order_ids)->field('name,phone_number,order_id')->select();
        $appends       = objectToArray($appends);
        $appends_map   = array_column($appends,null,'order_id');

        $ships         = Db::name('order_ship')->whereIn('order_id',$order_ids)->field('status as ship_status,time as ship_time,msg,type,order_id')->select();
        $ships         = objectToArray($ships);
        $ships_map     = array_column($ships,null,'order_id');

        $orders        = Db::name('order')->whereIn('order_id',$order_ids)->field('status as order_status,brush_status,shipping_type,tracking_number')->select();
        $orders        = objectToArray($orders);
        $orders_map    = array_column($orders,null,'order_id');



        $info         = Config::get('Logisticskey.' . 'warehouse_arr');
        $brush_info   = Config::get('Logisticskey.' . 'brush_list');
        $ship_info    = Config::get('Logisticskey.' . 'ship_status');

        if($list){
            foreach($list as $k=>$v){
                $shop_names    = $shopInfos_map[$v['shop_id']]??[];
                $appends_names = $appends_map[$v['order_id']]??[];
                $ships_names   = $ships_map[$v['order_id']]??[];
                $orders_info   = $orders_map[$v['order_id']]??[];
                $list[$k]['shop_name']     =  $shop_names['name']??'';
                $list[$k]['name']          =  $appends_names['name']??'';
                $list[$k]['phone_number']  =  $appends_names['phone_number']??'';
                $ship_status               =  $ships_names['ship_status']??'';
                $list[$k]['ship_status']   =  $ship_status  ? $ship_info[$ship_status]:'';
                $list[$k]['ship_time']     =  $v['update_time']??'';
                $list[$k]['createtime']    =  $v['created_time']??'';

                $brush_status     =  $orders_info['brush_status']??'';
                $list[$k]['tracking_number']  =  $orders_info['tracking_number']??'';
                $list[$k]['order_status']     =  $orders_info['order_status']??'';
                $list[$k]['shipping_type']    =  $orders_info['brush_status']??'';

                $list[$k]['msg']           =  $v['msg']??'';
                $list[$k]['type']          =  $ships_names['type']??'';
                $list[$k]['skus_info']     =  $v['seller_sku'];
                $list[$k]['warehouse_name']=  $v['warehouse_id'] ? $info[$v['warehouse_id']]:'';
                $list[$k]['brush_status']  =  $brush_status ? $brush_info[$brush_status]:'';
            }
        }

        $header[] = ['店铺', 'shop_name'];
        $header[] = ['订单号', 'order_id'];
        $header[] = ['SKU详情', 'skus_info'];
        $header[] = ['订单状态', 'order_status'];
        $header[] = ['发货状态', 'ship_status'];
        $header[] = ['跟踪号', 'tracking_number'];
        $header[] = ['发货详情', 'msg'];
        $header[] = ['客户姓名', 'name'];
        $header[] = ['客户电话', 'phone_number'];
        $header[] = ['仓库', 'warehouse_name'];
        $header[] = ['创建时间', 'createtime'];
        $header[] = ['订单类型', 'brush_status'];
        $fileName = "export_order_ship_" . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }





    /**
     * @desc  物流日志写入
     * @date  2024/3/22 0022
     * @param $log
     * @return int|string
     * @author ligang
     */
    public static function insertOrderShipLog($log)
    {
        $arr['status']       = $log['code'];
        $arr['msg']          = $log['msg']??"";
        $arr['data']         = $log['data']??"";
        $arr['order_id']     = $log['order_id']??"";
        $arr['shop_id']      = $log['shop_id']??'';
        $arr['warehouse_id'] = $log['warehouse_id']??'';
        $arr['return']       = $log['return0']??'';
        $arr['time']         = time();
        $result              = Db::name('order_ship_log')->insert($arr);
        return $result;
    }

    /**
     * 自动发货
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function automaticShipping($params = [])
    {

        $ids        = $params['ids'];
        $warehouse  = $params['warehouse_id'];
        $golden_ant = $params['golden_ant']??'';
        $fail_status= $params['status']??'';
        htmlLog(['params'=>$params],OPERATE_LOG . date('Ym') . '/automaticShipping/' . date('Ymd') . '.txt');
        if (empty($warehouse)) {
            return json(DefaultResponse(201, true, '仓库数据错误请刷新'));
        }

        $ids = is_array($ids) ? $ids : explode(',', $ids);

        // update 2024-06-15 此时更新状态值
        Db::name('order')->whereIn('id',$ids)->update(['send_status'=>1]);

        $where[] = ['o.id', 'in', $ids];
        $field = [
            'o.order_id', 'o.status','o.fulfillment_type','o.brush_status','o.shop_id','a.name','a.state','a.city','a.county',
            's.status as tracking_beforehand','o.shipping_type','o.shipping_documents','o.tracking_number','s.type',
            'i.seller_sku as skuinfo','a.phone_number', 'a.buyer_email', 'a.postal_code','a.address_detail',
            'a.name','a.postal_code','a.region_code','a.state','a.city','a.postal_code','a.address_detail','a.phone_number',
        ];

        $items = Db::name('order')
            ->alias('o')
            ->leftJoin('ba_order_info i', 'i.order_id       = o.order_id')
            ->leftJoin('ba_order_append a', 'a.order_id = o.order_id')
            ->leftJoin('ba_order_ship s', 's.order_id = o.order_id')
            ->field($field)
            ->where($where)
            ->select();
        $items = objectToArray($items);
        if($warehouse==1){
            //JJS自发货
            self::hwcSend($ids,$warehouse,$items);
        }else{
            if (!empty($items)){
                foreach ($items as $item) {
                    $item['tracking_beforehand'] = $item['tracking_beforehand']  ?: 0;
                    if ($item['status'] == 'AWAITING_SHIPMENT' && $item['fulfillment_type'] !== 'FULFILLMENT_BY_TIKTOK') {
                        if (in_array($item['tracking_beforehand'], [0, 1, 2])) {
                           /* //准备发货或者异常订单才能重新发货
                            $update['status']        = ConstantOrderService::$ship_status_waiting;
                            $update['warehouse_id']  = $warehouse;
                            Db::name('order_ship')->where('order_id', $item['order_id'])->update($update);*/

                            if ($warehouse == 1 && $item['brush_status'] == 'normal'){
                                $log                 = array();
                                $log['code']         = 1;
                                $log['order_id']     = $item['order_id'];
                                $log['shop_id']      = $item['shop_id'];
                                $log['time']         = time();
                                $log['warehouse_id'] = $warehouse;
                                OrderShipLogic::insertOrderShipLog($log);
                            }

                            $orderData = $item;
                            $orderData['warehouse_id'] = $warehouse;
                            $orderData['type'] = 1; //自发货
                            $orderData['fail_status']  = $fail_status;
                            if (in_array($warehouse, [2, 4, 5]) && $item['brush_status'] == 'normal' || $warehouse == 3){
                                // 队列处理
                                if ($warehouse == 3){
                                    $orderData['golden_ant'] = $golden_ant;
                                }
                                MqTaskPushLogic::mq_task_push(
                                    '',
                                    MqQueueName::QUEUE_ORDER_SHIPPING_QUEUE,
                                    $orderData,
                                    false
                                );
                            }
                        }
                    }
                }
            }
        }
        return json(DefaultResponse(200, true, '操作成功!'));
    }



    /**
     *  异常订单 自动发货
     * @param $params
     */
    public function automaticSplitShipping($params = [])
    {

        $ids        = $params['ids'];
        $warehouse  = $params['warehouse_id'];
        $golden_ant = $params['golden_ant']??'';
        $fail_status= $params['status'];
        htmlLog(['params'=>$params],OPERATE_LOG . date('Ym') . '/automaticShipping/' . date('Ymd') . '.txt');
        if (empty($warehouse)) {
            return json(DefaultResponse(201, true, '仓库数据错误请刷新'));
        }

        $ids = is_array($ids) ? $ids : explode(',', $ids);
        $where[] = ['s.id', 'in', $ids];

        $field = [
            'o.order_id', 'o.status','o.brush_status','o.fulfillment_type','o.shop_id','a.name','a.state','a.city','a.county',
            'o.shipping_type','o.shipping_documents','o.tracking_number','s.seller_sku as skuinfo',
            'a.phone_number', 'a.buyer_email', 'a.postal_code','a.address_detail',
        ];

        $items = Db::name('order_split_ship')
            ->alias('s')
            ->leftJoin('ba_order o', 's.order_id = o.order_id')
            ->leftJoin('ba_order_append a', 'a.order_id = o.order_id')
            ->field($field)
            ->where($where)
            ->select();
        $items = objectToArray($items);
        if($warehouse==1){
            //JJS自发货
            self::hwcSend($ids,$warehouse,$items);
        }else{
            if (!empty($items)){
                foreach ($items as $item) {
                    if ($item['status'] == 'AWAITING_SHIPMENT' && $item['fulfillment_type'] !== 'FULFILLMENT_BY_TIKTOK') {
                            if ($warehouse == 1 && $item['brush_status'] == 'normal'){
                                $log                 = array();
                                $log['code']         = 1;
                                $log['order_id']     = $item['order_id'];
                                $log['shop_id']      = $item['shop_id'];
                                $log['time']         = time();
                                $log['warehouse_id'] = $warehouse;
                                OrderShipLogic::insertOrderShipLog($log);
                            }

                            $orderData = $item;
                            $orderData['warehouse_id'] = $warehouse;
                            $orderData['type'] = 1; //自发货
                            $orderData['tracking_beforehand'] = 2;
                            $orderData['fail_status']  = $fail_status;
                            if (in_array($warehouse, [2, 4, 5]) && $item['brush_status'] == 'normal' || $warehouse == 3){
                                // 队列处理
                                if ($warehouse == 3){
                                    $orderData['golden_ant'] = $golden_ant;
                                }
                                MqTaskPushLogic::mq_task_push(
                                    '',
                                    MqQueueName::QUEUE_ORDER_SHIPPING_QUEUE,
                                    $orderData,
                                    false
                                );
                            }

                    }
                }
            }
        }
        return json(DefaultResponse(200, true, '操作成功!'));
    }



    /**
     * 强制发货
     * @param $params
     */
    public function mandatoryShipping($params = [])
    {
        $ids        = $params['ids'];
        $warehouse  = $params['warehouse_id'];
        $golden_ant = $params['golden_ant'];
        $fail_status= $params['status']??'';
        htmlLog(['params'=>$params],OPERATE_LOG . date('Ym') . '/mandatoryShipping/' . date('Ymd') . '.txt');
        if (empty($warehouse)) {
            return json(DefaultResponse(201, true, '仓库数据错误请刷新'));
        }
        $ids = is_array($ids) ? $ids : explode(',', $ids);

        //update  2024-04-29 此时先更新状态值;
        Db::name('order')->whereIn('id',$ids)->update(['send_status'=>1]);


        $where[] = ['o.id', 'in', $ids];
        $field = [
            'o.order_id', 'o.status','o.brush_status','o.fulfillment_type','o.shop_id','a.name','a.state','a.city','a.county',
             'o.shipping_type','o.shipping_documents','o.tracking_number','s.type',
            'i.seller_sku as skuinfo','a.phone_number', 'a.buyer_email', 'a.postal_code','a.address_detail',
        ];
        $items = Db::name('order')
            ->alias('o')
            ->leftJoin('ba_order_info i', 'i.order_id       = o.order_id')
            ->leftJoin('ba_order_append a', 'a.order_id = o.order_id')
            ->leftJoin('ba_order_ship s', 's.order_id = o.order_id')
            ->field($field)
            ->where($where)
            ->select();
        $items = objectToArray($items);
        if (!empty($items)) {
            foreach ($items as $item) {
                if ($item['fulfillment_type'] !== 'FULFILLMENT_BY_TIKTOK') {
                    //准备发货或者异常订单才能重新发货
                   /* $update['status']        = ConstantOrderService::$ship_status_waiting;
                    $update['warehouse_id']  = $warehouse;
                    Db::name('order_ship')->where('order_id', $item['order_id'])->update($update);*/

                    // 队列处理
                    $orderData = $item;
                    if ($warehouse == 3){
                        $orderData['golden_ant'] = $golden_ant;
                    }

                    if(in_array($warehouse, [3, 4])){
                        $orderData['warehouse_id'] = $warehouse;
                        $orderData['type']         = 2;
                        $orderData['fail_status']  = $fail_status;
                        MqTaskPushLogic::mq_task_push(
                            '',
                            MqQueueName::QUEUE_ORDER_SHIPPING_QUEUE,
                            $orderData,
                            false
                        );
                    }
                }
            }
        }
        //直接触发MQ消费 2024-05-14
        //(new OrderBtLogic())->getCrontab();
        return json(DefaultResponse(200, true, '操作成功!'));
    }




    /**
     * 异常订单 强制发货
     * @param $params
     */
    public function mandatorySplitShipping($params = [])
    {
        $ids        = $params['ids'];
        $warehouse  = $params['warehouse_id'];
        $golden_ant = $params['golden_ant'];
        $fail_status= $params['status'];
        htmlLog(['params'=>$params],OPERATE_LOG . date('Ym') . '/mandatorySplitShipping/' . date('Ymd') . '.txt');
        if (empty($warehouse)) {
            return json(DefaultResponse(201, true, '仓库数据错误请刷新'));
        }
        $ids = is_array($ids) ? $ids : explode(',', $ids);


        $where[] = ['s.id', 'in', $ids];

        $field = [
            'o.order_id', 'o.status','o.brush_status','o.fulfillment_type','o.shop_id','a.name','a.state','a.city','a.county',
            'o.shipping_type','o.shipping_documents','o.tracking_number','s.seller_sku as skuinfo',
            'a.phone_number', 'a.buyer_email', 'a.postal_code','a.address_detail',
        ];

        $items = Db::name('order_split_ship')
            ->alias('s')
            ->leftJoin('ba_order o', 's.order_id = o.order_id')
            ->leftJoin('ba_order_append a', 'a.order_id = o.order_id')
            ->field($field)
            ->where($where)
            ->select();
        $items = objectToArray($items);
        if (!empty($items)) {
            foreach ($items as $item) {
                if ($item['fulfillment_type'] !== 'FULFILLMENT_BY_TIKTOK') {
                    Db::name('order_ship')->where('order_id', $item['order_id'])
                        ->update(['status'=>5]);


                    // 队列处理
                    $orderData = $item;
                    if ($warehouse == 3){
                        $orderData['golden_ant'] = $golden_ant;
                    }
                    if(in_array($warehouse, [3, 4])){
                        $orderData['warehouse_id'] = $warehouse;
                        $orderData['type']         = 2;
                        $orderData['tracking_beforehand'] = 2;
                        $orderData['fail_status']  = $fail_status;
                        MqTaskPushLogic::mq_task_push(
                            '',
                            MqQueueName::QUEUE_ORDER_SHIPPING_QUEUE,
                            $orderData,
                            false
                        );
                    }
                }
            }
        }

        //直接触发MQ消费 2024-05-14
        //(new OrderBtLogic())->getCrontab();
        return json(DefaultResponse(200, true, '操作成功!'));
    }




    /**
     * @desc  海外仓发货JJS
     * @Date  2024-04-15
     * @author luckyXiong
     */
    public function hwcSend($ids,$warehouse,$items)
    {
        if(!$items)        return json(DefaultResponse(201, false, '暂无数据!'));
        foreach($items as $order){
              self::hwc_send_handle($order);
        }
    }



    /**
     * @desc  海外仓发货JJS
     * @Date  2024-04-15
     * @author luckyXiong
     */
    public function hwc_send_handle($order=[]){
        htmlLog(['order'=>$order],OPERATE_LOG . date('Ym') . '/hwc_send_handle/' . date('Ymd') . '.txt');
        $ParamsJson = self::get_params_jjs($order);
        $Params     = self::get_hwc_jjs($order);
        $msg_hwc    = $ParamsJson ? '':'海外仓找不到SKU：' . $order['skuinfo'];
        $ParamsJson["OrderDetail"][] = $Params;
        if($ParamsJson){
           Db::name('order_ship')->where('order_id', $order['order_id'])->update([
               'status'=> 2,
               'time'  => time(),
               'msg'   => $msg_hwc
           ]
           );
           $log['code']         = 1;
           $log['order_id']     = $order['order_id'];
           $log['shop_id']      = $order['shop_id'];
           $log['time']         = time();
           $log['warehouse_id'] = 1;;
           OrderShipLogic::insertOrderShipLog($log);
       }

        // 重量小于0.448的全选小包
        if ($Params['zWeight'] > 0.448) {
            $ParamsJson["ShipperService"] = "796"; //运输方式 大包
        } else {
            $ParamsJson["ShipperService"] = "797"; //运输方式 小包
        }

        $ParamsJson = (is_array($ParamsJson)) ? json_encode($ParamsJson, JSON_UNESCAPED_UNICODE) : $ParamsJson;
        $url        = Config('Logisticskey.JJS.url');
        $token      = Config('Logisticskey.JJS.token');
        $data =[
            'token'      => $token,
            'ParamsJson' => $ParamsJson,
        ];

        $data     = http_build_query($data);
        $response = HttpUtil::posturlJJS($url, $data);
        $return   = json_decode(json_encode(simplexml_load_string($response)), true);
        $return   = $return[0]??'';
        if(!$return) return json(DefaultResponse(201, false, '暂无数据!'));
        $return = json_decode($return,'true');
        if(isset($return['OrderNo']) && $return['OrderNo']){
            $return['code']    = 3;
            $return['msg']     = "回传物流单号";
            $return['data']    = $return['TrackingNo'];
            $return['return1'] = json_encode($ParamsJson, true);
            Db::name('order')->where('order_id', $order['order_id'])->update(
                [
                    'status'              => 'AWAITING_COLLECTION',
                    'tracking_number'     =>  $return['TrackingNo'],
                ]
            );
            Db::name('order_ship')->where('order_id', $order['order_id'])->update(
                [
                    'status'              =>  4,
                    'tracking_number'     =>  $return['TrackingNo'],
                    'msg'                 =>  '物流单号回传完成',
                    'time'                =>  time(),
                ]
            );
            $log['code']         = 3;
            $log['order_id']     = $order['order_id'];
            $log['shop_id']      = $order['shop_id'];
            $log['msg']          = '物流单号回传完成';
            $log['time']         = time();
            $log['warehouse_id'] = 1;;
            self::insertOrderShipLog($log);
        }else{
            Db::name('order_ship')->where('order_id', $order['order_id'])->update(
                [
                    'status'              =>  2,
                    'msg'                 =>  $return['msg'],
                    'time'                =>  time(),
                ]
            );
            $log['code']         = 2;
            $log['order_id']     = $order['order_id'];
            $log['shop_id']      = $order['shop_id'];
            $log['time']         = time();
            $log['msg']          = $return['msg'];
            $log['warehouse_id'] = 1;;
            self::insertOrderShipLog($log);
        }
    }




    /**
     * @desc  获取组装数据
     * @Date  2024-04-15
     * @author luckyXiong
     */
    private function get_params_jjs($order=[]){
        return [
            "Style"         =>1,
            "CsRefNo"       =>$order['order_id']??'',
            "StockID"       =>"35",
            "ConsigneeName" =>$order['name']??'',
            "CountryCode"   =>$order['region_code']??'',
            "State"         =>$order['state']??'',
            "City"          =>$order['city']??'',
            "Zipcode"       =>$order['postal_code']??'',
            "Address1"      =>$order['address_detail']??'',
            "Contact"       =>$order['phone_number']??'',
            "Signature"     =>"0",
            "Insurance"     =>"0",
        ];
    }

    /**
     * @desc  获取组装数据
     * @Date  2024-04-15
     * @author luckyXiong
     */
    private function get_hwc_jjs($order=[]){
        $product_hwc =  Db::name('product_hwc')->where('CnName', $order['skuinfo'])->find();
        $zWeight = 0;
        $OrderDetail["CnName"]   = $product_hwc['CnName'];
        $OrderDetail["EnName"]   = $product_hwc['EnName'];
        $OrderDetail["SKU"]      = $product_hwc['SKU'];
        $OrderDetail["Quantity"] = get_colours_num($order['skuinfo']);
        $OrderDetail["Weight"]   = $product_hwc['Weight'];
        $OrderDetail["zWeight"] = (float)number_format((float)$zWeight + (float)$OrderDetail["Weight"], 2, '.', '');
        $OrderDetail["Length"] = $product_hwc['Length'];
        $OrderDetail["Width"] = $product_hwc['Width'];
        $OrderDetail["High"] = $product_hwc['High'];
        $OrderDetail["Price"] = $product_hwc['Price'];
        $OrderDetail["CnName"] = $product_hwc['CnName'];
        $OrderDetail["HSCode"] = "";
        $OrderDetail["Origin"] = "";
        return $OrderDetail;
    }










    /**
     * 订单导出
     * @param $params
     * @return \think\response\Json
     */
    public function exportOrder($params = [])
    {
        $shop_id         = $params['shop_name_arr'] ?? '0';
        $orderId         = $params['order_id'] ?? '';
        $seller_sku      = $params['skus_info'] ?? '';
        $status          = $params['status'] ?? '';
        $shipping_type   = $params['shipping_type'] ?? '';
        $tracking_number = $params['tracking_number'] ?? '';
        $warehouse_id    = $params['warehouse_id'] ?? '';
        $createtime      = $params['createtime'] ?? '';
        $ship_time       = $params['ship_time'] ?? '';

        $brush_status    = $params['brush_status'] ?? '';
        $limit           = $params['limit'] ?? 10;

        $where           = [];
        $order = ['order.createtime' => 'desc', 'order.id' => 'desc'];


        if ($orderId) {
            $order_ids = trim($orderId);
            $order_ids = array_filter(array_map('trim', explode("\n", $order_ids)));
            if (!empty($order_ids)) {
                $where[] = ['order.order_id', 'in', $order_ids];
            }
        }

        if ($shop_id) {
            $where[] = ['order.shop_id', '=',$shop_id];
        }

        if($seller_sku) {
            $orderIds = Db::name('order_info')
                ->where('seller_sku', 'like', '%' . $seller_sku . '%')
                ->column('order_id');
            $orderIds = array_unique($orderIds);
            if ($orderIds) {
                $where[] = ['order.order_id', 'in', $orderIds];
            }
        }

        //update 2024-05-16 异常重发导出页面
        if($status == 6){
            $map = [];
            return self::get_export_six($map,$limit,$warehouse_id,$orderId);
        }

        if ($status) {
            $where[] = ['ship.status', '=', $status];
        }else{
            $where[] = ['ship.status', '>=', 1];
        }

        if ($brush_status) {
            $where[] = ['order.brush_status', '=', $brush_status];
        }

        if ($shipping_type) {
            $where[] = ['order.shipping_type', '=', $shipping_type];
        }


        if ($tracking_number) {
            $where[] = ['order.tracking_number', 'like', '%' . $tracking_number . '%'];
        }
        if ($warehouse_id) {
            $where[] = ['ship.warehouse_id', '=', $warehouse_id];
        }
        if ($createtime) {
            $createTimeArr = explode(',', $createtime);
            $where[] = ['order.createtime', '>=', strtotime($createTimeArr[0])];
            $where[] = ['order.createtime', '<=', strtotime($createTimeArr[1])];
        }
        if ($ship_time) {
            $shipTimeArr = explode(',', $ship_time);
            $where[] = ['ship.time', '>=', strtotime($shipTimeArr[0])];
            $where[] = ['ship.time', '<=', strtotime($shipTimeArr[1])];
        }

        $field = [
            'order.id','order.order_id','order.shop_id','ship.warehouse_id',
            'ship.status as ship_status','ship.time as ship_time','ship.msg','ship.type',
            'order.createtime','order.brush_status','order.tracking_number','order.status as order_status',
            'appends.name','appends.phone_number','order.shipping_type','order.status as order_status'
        ];

        $res =  Db::name('order')
            ->alias('order')
            ->leftJoin('ba_order_append appends', 'order.order_id = appends.order_id')
            ->leftJoin('ba_order_ship ship', 'order.order_id = ship.order_id')
            ->field($field)
            ->where($where)
            ->select();

        $list      = objectToArray($res)?:[];
        if(!$list)   return json(DefaultResponse(201, false, '暂无可导出数据!'));

        $shop_ids  = array_column($list,'shop_id');
        $shop_ids  = array_values(array_unique($shop_ids));

        $order_ids = array_column($list,'order_id');
        $order_ids = array_values(array_unique($order_ids));


        //批量获取店铺信息及sku数量信息;
        $shopInfos     = Db::name('shops')->whereIn('id',$shop_ids)->field('name,id')->select();
        $shopInfos     = objectToArray($shopInfos);
        $shopInfos_map = array_column($shopInfos,null,'id');

        //批量获取sku数量数据;
        $skuInfos     = Db::name('order_info')->whereIn('order_id',$order_ids)->field('seller_sku,order_id')->select();
        $skuInfos     = objectToArray($skuInfos);
        $skuInfos_map = self::get_sku_info($skuInfos);
        $info         = Config::get('Logisticskey.' . 'warehouse_arr');
        $brush_info   = Config::get('Logisticskey.' . 'brush_list');
        $ship_info    = Config::get('Logisticskey.' . 'ship_status');

        foreach($list as $k=>$v){
                $shop_names = $shopInfos_map[$v['shop_id']]??[];
                $sku_names = $skuInfos_map[$v['order_id']]??[];
                $list[$k]['shop_name']     =  $shop_names['name']??'';
                $list[$k]['skus_info']     =  $sku_names ? implode(',',$sku_names):'';
                $list[$k]['warehouse_name']=  $v['warehouse_id'] ? $info[$v['warehouse_id']]:'';
                $list[$k]['brush_status']  =  $v['brush_status'] ? $brush_info[$v['brush_status']]:'';
                $list[$k]['ship_status']   =  $v['ship_status']  ? $ship_info[$v['ship_status']]:'';
                $list[$k]['createtime']    =  $v['createtime'] ? date("Y-m-d H:i:s", $v['createtime']):'';
            }


        $header[] = ['店铺', 'shop_name'];
        $header[] = ['订单号', 'order_id'];
        $header[] = ['SKU详情', 'skus_info'];
        $header[] = ['订单状态', 'order_status'];
        $header[] = ['发货状态', 'ship_status'];
        $header[] = ['发货信息', 'msg'];
        $header[] = ['跟踪号', 'tracking_number'];
        $header[] = ['发货详情', 'msg'];
        $header[] = ['客户姓名', 'name'];
        $header[] = ['客户电话', 'phone_number'];
        $header[] = ['仓库', 'warehouse_name'];
        $header[] = ['创建时间', 'createtime'];
        $header[] = ['订单类型', 'brush_status'];
        $fileName = "export_order_ship_" . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    /**
     * @desc  结束发货
     * @date  2024/3/22 0022
     * @param $params
     * @return \think\response\Json
     * @author ligang
     */
    public function endShipping($params)
    {
        $id        = $params['ids'];
        $status    = $params['status']??'';
        $ids       = is_array($id) ? $id : explode(',', $id);
        $items     = Db::name('order')->where("id", "in", $ids)->select();
        $items     = objectToArray($items);
        $order_ids = array_column($items,'order_id');

        if($status==6){
            Db::name('order_split_ship')->whereIn('id', $ids)->update(
                [
                    'status'         => 1,
                    'update_time'    => date("Y-m-d H:i:s", time()),
                ]
            );
        }else{
            Db::name('order')
                ->whereIn('id', $ids)
                ->update(
                    ['shipping_documents_status' => 6]
                );

            Db::name('order_ship')->whereIn('order_id', $order_ids)->update(
                [
                    'status' => 6,
                    'time'   =>time(),
                ]
            );
        }
        return json(DefaultResponse(200, true, '操作成功'));
    }


    /**
     * @desc获取sku信息
     * @date  2024-03-28
     * @author  luckyXiong
     */
    public function get_sku_info($originalArray=[]){
        $newArray = [];
        foreach ($originalArray as $item) {
            $orderId = $item['order_id'];
            unset($item['order_id']);

            if (!isset($newArray[$orderId])) {
                $newArray[$orderId] = [];
            }

            $newArray[$orderId][] = $item['seller_sku'];
        }
        foreach ($newArray as &$values) {
            $values = array_combine(range(0, count($values) - 1), array_values($values));
        }
        return  $newArray;
    }


    /**
     * @desc  异常重发详情信息
     * @date  2024-05-11
     * @author  luckyXiong
     */
    public function splitOrderInfo($info=[]){

        $id = $info['id']??'';

        $field = [
            's.id','s.order_id','s.shop_id','s.warehouse_id','s.seller_sku','s.created_time','s.msg',
            'order.createtime','order.brush_status','order.tracking_number','order.status as order_status','order.shipping_type',
        ];
        $order   = ['order.createtime' => 'desc', 'order.id' => 'desc'];
        $where[] = ['s.status', '=', 0];
        $where[] = ['s.id', '=', $id];
        $list    = Db::name('order_split_ship')
            ->alias('s')
            ->leftJoin('ba_order order', 's.order_id = order.order_id')
            ->field($field)
            ->where($where)
            ->order($order)
            ->find();

        //批量获取店铺信息;
        $shopInfos     = Db::name('shops')->where('id',$list['shop_id'])->field('name,id')->find();
        $field         = ['name,phone_number,order_id,postal_code,buyer_email,region_code,delivery_option_name,payment_method_name,country,state,county,city,address_detail'];
        $appends       = Db::name('order_append')->where('order_id',$list['order_id'])->field($field)->find();
        $ships         = Db::name('order_ship')->where('order_id',$list['order_id'])->field('status as ship_status,time as ship_time,msg,type,order_id')->find();

        $info         = Config::get('Logisticskey.' . 'warehouse_arr');
        $brush_info   = Config::get('Logisticskey.' . 'brush_list');
        $ship_info    = Config::get('Logisticskey.' . 'ship_status');

        $list['shop_name']     =  $shopInfos['name']??'';
        $list['name']          =  $appends['name']??'';
        $list['phone_number']  =  $appends['phone_number']??'';
        $list['county']  =  $appends['county']??'';
        $list['region_code']  =  $appends['region_code']??'';
        $list['postal_code']  =  $appends['postal_code']??'';
        $list['buyer_email']  =  $appends['buyer_email']??'';
        $list['delivery_option_name']  =  $appends['delivery_option_name']??'';
        $list['payment_method_name']  =  $appends['payment_method_name']??'';
        $list['country']  =  $appends['country']??'';
        $list['state']  =  $appends['state']??'';
        $list['county']  =  $appends['county']??'';
        $list['city']  =  $appends['city']??'';
        $list['address_detail']  =  $appends['address_detail']??'';
        $ship_status           =  $ships['ship_status']??'';
        $list['ship_status']   =  $ship_status  ? $ship_info[$ship_status]:'';
        $list['ship_time']     =  $list['update_time']??'';
        $list['createtime']    =  $list['created_time']??'';
        $list['msg']           =  $list['msg']??'';
        $list['type']          =  $ships['type']??'';
        $list['skus_info']     =  $list['seller_sku'];
        $list['warehouse_name']=  $list['warehouse_id'] ? $info[$list['warehouse_id']]:'';
        $list['brush_status']  =  $list['brush_status'] ? $brush_info[$list['brush_status']]:'';
        return   $list;
    }
}
